var exec = require("child_process").exec;
var formidable = require('formidable');
var util = require('util');
var fs = require("fs");

var _savefilepath = __dirname + "/tmp/";
if(!fs.existsSync(_savefilepath))
{
	fs.mkdirSync(_savefilepath);
}

function home(urlpath, request, response){	
	var body = '<html>'+
		'<head><title>'+urlpath+'</title>'+
		'<meta http-equiv="Content-Type" content="text/html; '+
		'charset=UTF-8" />'+
		'</head>'+
		'<body>'+
		'<form action="/upload" enctype="multipart/form-data" method="post">'+
	    'Title: <input type="text" name="title"><br/>'+
	    'NiceName: <input type="text" name="NiceName"><br/>'+
	    '<input type="file" name="upload" multiple="multiple"><br>'+
		'<input type="submit" value="Submit text" />'+
		'</form>'+
		'</body>'+
		'</html>';	

	request.setEncoding("utf-8");
	response.writeHead(200, {'Content-Type': 'text/htm; charset=utf-8l'});
	response.end(body);
}

function start(urlpath, request, response) {
  
	var content = urlpath;

	exec("ls -lah",function(error, stdout, stderr){
	    response.writeHead(200,{"Content-Type":"text/plain"});
	    response.write(stdout);
	    response.end(content);
	  });
  
}

function upload(urlpath, request, response) {
	var postData;

	request.addListener("data",function(postDataChunk){
		postData = postDataChunk;
		console.log("Received POST data chunk! " + postData.length);
	});
	
	request.addListener("end",function(){
		console.log('Received Post data end！');
	});
	
	if(request.url == '/upload' && request.method.toLowerCase() == 'post')
	{
	    var form = new formidable.IncomingForm();
	
		form.parse(request, function(err, fields, files) {
		
			// Upload files!
		  fs.renameSync(files.upload.path, _savefilepath + files.upload.name);
			
		  response.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
		  response.write('Error: '+util.inspect(err) + '\n\n');
		  response.write('received upload['+urlpath+']:\n');
		  response.end(util.inspect({forms: fields, files: files}));
		});
		return "Files uploaded!"
	}
	
	response.end('This method is ' + request.method + '!');
}

function show(urlpath, request, response)
{
	// Read files!
	fs.readFile(_savefilepath + "test.png","binary",function(error, file){
		if(error){
			response.writeHead(500,{"Content-Type":"text/plain"});
			response.write(error +"\n");
			response.end();
		}else{
			response.writeHead(200,{"Content-Type":"image/png"});
			response.write(file,"binary");
			response.end();
		}
	});
}

function p404(urlpath, request, response)
{
	request.setEncoding("utf-8");
	response.writeHead(200, {'Content-Type': 'text/plain'});
	response.end("[404] This page can't be displayed!");
}

exports.home = home;
exports.start = start;
exports.upload = upload;
exports.show = show;
exports.p404 = p404;